<template>
    <view class="container">
       
        <view class="month-selector">
            <view class="calendar-icon">
                <text class="tn-icon-calendar-fill"></text>
            </view>
            <view class="date-range">
                {{ currentYear }}-{{ currentMonth < 10 ? '0' + currentMonth : currentMonth }}-01 ~ {{ currentYear }}-{{ currentMonth < 10 ? '0' + currentMonth : currentMonth }}-{{
                    daysInMonth
                }}
            </view>
            <view class="selector-arrows">
                <text class="tn-icon-left" @tap="prevMonth"></text>
                <text class="tn-icon-right" @tap="nextMonth"></text>
            </view>
        </view>

       
        <scroll-view scroll-y class="date-cards">
            <view v-for="(date, index) in dateList" :key="index" class="date-card">
                <!-- 日期标题 -->
                <view class="date-header">
                    <view class="date-day">
                        <text class="date-icon">{{ date.day }}</text>
                    </view>
                    <view class="date-arrow">
                        <text class="tn-icon-right"></text>
                    </view>
                </view>

                <!-- 餐饮记录 -->
                <view class="meal-records">
                    <!-- 早餐 -->
                    <view class="meal-item" @tap="editMeal(date.fullDate, 'breakfast')">
                        <view class="meal-icon">
                            <text class="tn-icon-food-fill"></text>
                        </view>
                        <view class="meal-name">早餐</view>
                        <view class="meal-calories">
                            {{ getMealCalories(date.fullDate, 'breakfast') || '500千卡' }}
                        </view>
                    </view>

                    <!-- 午餐 -->
                    <view class="meal-item" @tap="editMeal(date.fullDate, 'lunch')">
                        <view class="meal-icon lunch-icon">
                            <text class="tn-icon-food"></text>
                        </view>
                        <view class="meal-name">午餐</view>
                        <view class="meal-calories">
                            {{ getMealCalories(date.fullDate, 'lunch') || '500千卡' }}
                        </view>
                    </view>

                    <!-- 晚餐 -->
                    <view class="meal-item" @tap="editMeal(date.fullDate, 'dinner')">
                        <view class="meal-icon dinner-icon">
                            <text class="tn-icon-food"></text>
                        </view>
                        <view class="meal-name">晚餐</view>
                        <view class="meal-calories">
                            {{ getMealCalories(date.fullDate, 'dinner') || '500千卡' }}
                        </view>
                    </view>

                    <!-- 加餐 -->
                    <view class="meal-item" @tap="editMeal(date.fullDate, 'snack')">
                        <view class="meal-icon snack-icon">
                            <text class="tn-icon-food"></text>
                        </view>
                        <view class="meal-name">加餐</view>
                        <view class="meal-calories">
                            {{ getMealCalories(date.fullDate, 'snack') || '无记录' }}
                        </view>
                    </view>
                </view>

                <!-- 删除按钮 -->
                <view class="delete-btn" @tap="deleteMealRecord(date.fullDate)">
                    <text class="tn-icon-delete"></text>
                </view>
            </view>
        </scroll-view>

        <!-- 食物选择弹窗 -->
        <tn-popup mode="bottom" :value="popupVisible" @input="(val) => (popupVisible = val)" closeBtn safeAreaInsetBottom borderRadius="24">
            <view class="food-popup">
                <view class="popup-title">
                    {{ currentMealType === 'breakfast' ? '早餐' : currentMealType === 'lunch' ? '午餐' : currentMealType === 'dinner' ? '晚餐' : '加餐' }}记录
                </view>
                <view class="popup-date">{{ currentDate }}</view>

                <view class="food-search">
                    <tn-input v-model="searchKeyword" placeholder="搜索食物" border></tn-input>
                </view>

                <scroll-view scroll-y class="food-list">
                    <view v-for="(food, index) in filteredFoodList" :key="index" class="food-item" @tap="selectFood(food)">
                        <view class="food-name">{{ food.names }}</view>
                        <view class="food-calories">{{ food.reliangNum }}千卡 / {{food.weight+food.units}}</view>
                    </view>
                </scroll-view>

                <view class="selected-foods" v-if="selectedFoods.length > 0">
                    <view class="selected-title">已选择食物</view>
                    <view v-for="(item, index) in selectedFoods" :key="index" class="selected-food-item">
                        <view class="selected-food-name">{{ item.food.names }}</view>
                        <!-- <view class="selected-food-amount">
                            <text class="amount-btn" @tap="decreaseAmount(index)">-</text>
                            <text class="amount-value">{{ item.amount }}</text>
                            <text class="amount-btn" @tap="increaseAmount(index)">+</text>
                        </view> -->
                        <view class="selected-food-calories">{{ (item.food.reliangNum * item.amount).toFixed(0) }}千卡</view>
                        <text class="remove-btn tn-icon-close" @tap="removeFood(index)"></text>
                    </view>

                    <view class="total-calories">总热量: {{ getTotalCalories() }}千卡</view>
                </view>

                <view class="popup-actions">
                    <view class="save-btn" @tap="saveMealRecord">保存</view>
                </view>
            </view>
        </tn-popup>
    </view>
</template>

<script>
import foodList from './static/foodData.json';

export default {
    data() {
        return {
            currentYear: new Date().getFullYear(),
            currentMonth: new Date().getMonth() + 1,
            dateList: [],
            daysInMonth: 31,
            mealRecords: {},
            popupVisible: false,
            currentDate: '',
            currentMealType: '',
            searchKeyword: '',
            selectedFoods: []
        };
    },
    computed: {
        filteredFoodList() {
            if (!this.searchKeyword) return [];
            return foodList.filter(food =>
              food.names.toLowerCase().includes(this.searchKeyword.toLowerCase())
            );
        }
    },
    onLoad() {
        this.initDateList();
        //  this.loadMealRecords();
    },
    methods: {
        navBack() {
            uni.navigateBack();
        },

        // 初始化日期列表
        initDateList() {
            const date = new Date(this.currentYear, this.currentMonth - 1, 1);
            const lastDay = new Date(this.currentYear, this.currentMonth, 0).getDate();
            this.daysInMonth = lastDay;
            ;
            var temp = [];
            for (let i = lastDay; i >= 1; i--) {
                const fullDate = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}-${i < 10 ? '0' + i : i}`;
                temp.push({
                    day: i,
                    fullDate
                });
            }
            this.dateList = temp;
            console.log(this.dateList);
        },

        // 上个月
        prevMonth() {
            if (this.currentMonth === 1) {
                this.currentYear--;
                this.currentMonth = 12;
            } else {
                this.currentMonth--;
            }
            this.initDateList();
            this.loadMealRecords();
        },

        // 下个月
        nextMonth() {
            if (this.currentMonth === 12) {
                this.currentYear++;
                this.currentMonth = 1;
            } else {
                this.currentMonth++;
            }
            this.initDateList();
            this.loadMealRecords();
        },

        // 加载餐饮记录
        loadMealRecords() {
            const monthDate = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}`;
            const user = uni.getStorageSync('user');

            if (user) {
                // 从本地存储加载数据，实际项目中应该从服务器获取
                const storageKey = `meal_records_${user._id}_${monthDate}`;
                const records = uni.getStorageSync(storageKey);
                if (records) {
                    this.mealRecords = JSON.parse(records);
                } else {
                    this.mealRecords = {};
                }
            }
        },

        // 获取餐饮热量
        getMealCalories(date, mealType) {
            if (this.mealRecords[date] && this.mealRecords[date][mealType]) {
                const foods = this.mealRecords[date][mealType];
                let totalCalories = 0;
                foods.forEach((item) => {
                    totalCalories += item.food.calories * item.amount;
                });
                return `${totalCalories.toFixed(0)}千卡`;
            }
            return null;
        },

        // 编辑餐饮
        editMeal(date, mealType) {
            this.currentDate = date;
            this.currentMealType = mealType;
            this.selectedFoods = [];

            // 加载已有的食物记录
            if (this.mealRecords[date] && this.mealRecords[date][mealType]) {
                this.selectedFoods = JSON.parse(JSON.stringify(this.mealRecords[date][mealType]));
            }

            this.popupVisible = true;
        },

        // 选择食物
        selectFood(food) {
            // 检查是否已经选择了该食物
            const existingIndex = this.selectedFoods.findIndex((item) => item.food.names === food.names);

            if (existingIndex >= 0) {
                // 如果已经选择了，增加数量
                this.selectedFoods[existingIndex].amount += 1;
            } else {
                // 否则添加到已选择列表
                this.selectedFoods.push({
                    food,
                    amount: 1
                });
            }

            console.log(this.selectedFoods);
        },

        // 增加食物数量
        increaseAmount(index) {
            this.selectedFoods[index].amount += 1;
        },

        // 减少食物数量
        decreaseAmount(index) {
            if (this.selectedFoods[index].amount > 1) {
                this.selectedFoods[index].amount -= 1;
            }
        },

        // 移除食物
        removeFood(index) {
            this.selectedFoods.splice(index, 1);
        },

        // 计算总热量
        getTotalCalories() {
            let total = 0;
            this.selectedFoods.forEach((item) => {
                total += item.food.reliangNum * item.amount;
            });
            return total.toFixed(0);
        },

        // 保存餐饮记录
        saveMealRecord() {
            if (!this.mealRecords[this.currentDate]) {
                this.mealRecords[this.currentDate] = {};
            }

            this.mealRecords[this.currentDate][this.currentMealType] = this.selectedFoods;

            // 保存到本地存储，实际项目中应该保存到服务器
            const user = uni.getStorageSync('user');
            if (user) {
                const monthDate = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}`;
                const storageKey = `meal_records_${user._id}_${monthDate}`;
                uni.setStorageSync(storageKey, JSON.stringify(this.mealRecords));

                uni.showToast({
                    title: '保存成功',
                    icon: 'success'
                });

                this.popupVisible = false;
            } else {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                });
            }
        },

        // 删除餐饮记录
        deleteMealRecord(date) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这一天的所有餐饮记录吗？',
                success: (res) => {
                    if (res.confirm) {
                        if (this.mealRecords[date]) {
                            delete this.mealRecords[date];

                            // 保存到本地存储
                            const user = uni.getStorageSync('user');
                            if (user) {
                                const monthDate = `${this.currentYear}-${this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth}`;
                                const storageKey = `meal_records_${user._id}_${monthDate}`;
                                uni.setStorageSync(storageKey, JSON.stringify(this.mealRecords));

                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'success'
                                });
                            }
                        }
                    }
                }
            });
        }
    }
};
</script>

<style lang="scss">
.container {
    min-height: 100vh;
    background-color: #f8f9fc;
    padding-bottom: 40rpx;
}

.status-bar {
    background-color: #fff;
    padding-top: env(safe-area-inset-top);
    padding-bottom: 20rpx;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    padding-right: 30rpx;
    position: relative;

    .nav-back {
        position: absolute;
        left: 30rpx;
        font-size: 40rpx;
        color: #333;
    }

    .title {
        flex: 1;
        text-align: center;
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }
}

.month-selector {
    margin: 30rpx;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .calendar-icon {
        color: #ff6b35;
        font-size: 40rpx;
        margin-right: 20rpx;
    }

    .date-range {
        flex: 1;
        font-size: 28rpx;
        color: #333;
    }

    .selector-arrows {
        display: flex;
        align-items: center;

        .tn-icon-left,
        .tn-icon-right {
            font-size: 32rpx;
            color: #666;
            padding: 10rpx;
        }
    }
}

.date-cards {
    height: calc(100vh - 240rpx);
    padding: 0 30rpx;
}

.date-card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    position: relative;

    .date-header {
        padding: 20rpx 30rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f5f5f5;

        .date-day {
            display: flex;
            align-items: center;

            .date-icon {
                width: 60rpx;
                height: 60rpx;
                background-color: #ff6b35;
                color: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 28rpx;
                margin-right: 20rpx;
            }
        }

        .date-arrow {
            color: #999;
            font-size: 32rpx;
        }
    }

    .meal-records {
        display: flex;
        flex-wrap: wrap;
        padding: 20rpx;
    }

    .meal-item {
        width: 50%;
        padding: 20rpx;
        display: flex;
        align-items: center;

        .meal-icon {
            width: 60rpx;
            height: 60rpx;
            background-color: rgba(255, 107, 53, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ff6b35;
            font-size: 32rpx;
            margin-right: 20rpx;
        }

        .lunch-icon {
            background-color: rgba(255, 172, 0, 0.1);
            color: #ffac00;
        }

        .dinner-icon {
            background-color: rgba(251, 106, 103, 0.1);
            color: #fb6a67;
        }

        .snack-icon {
            background-color: rgba(149, 123, 254, 0.1);
            color: #957bfe;
        }

        .meal-name {
            font-size: 28rpx;
            color: #333;
            margin-right: 20rpx;
        }

        .meal-calories {
            font-size: 24rpx;
            color: #999;
        }
    }

    .delete-btn {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        width: 60rpx;
        height: 60rpx;
        background-color: #ff6b35;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 32rpx;
    }
}

.food-popup {
    padding: 30rpx;
    .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
        text-align: center;
    }

    .popup-date {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 30rpx;
        text-align: center;
    }

    .food-search {
        margin-bottom: 20rpx;
    }

    .food-list {
        height: 30vh;
        margin-bottom: 30rpx;
    }

    .food-item {
        padding: 20rpx 0;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        justify-content: space-between;

        .food-name {
            font-size: 28rpx;
            color: #333;
        }

        .food-calories {
            font-size: 24rpx;
            color: #999;
        }
    }

    .selected-foods {
        margin-top: 30rpx;
        padding-top: 30rpx;
        border-top: 1px solid #f5f5f5;
        height: 20vh;
        overflow: auto;
        .selected-title {
            font-size: 28rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }

        .selected-food-item {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            border-bottom: 1px solid #f5f5f5;

            .selected-food-name {
                flex: 1;
                font-size: 28rpx;
                color: #333;
            }

            .selected-food-amount {
                display: flex;
                align-items: center;
                margin-right: 20rpx;

                .amount-btn {
                    width: 50rpx;
                    height: 50rpx;
                    background-color: #f5f5f5;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 28rpx;
                }

                .amount-value {
                    margin: 0 20rpx;
                    font-size: 28rpx;
                }
            }

            .selected-food-calories {
                font-size: 24rpx;
                color: #ff6b35;
                margin-right: 20rpx;
            }

            .remove-btn {
                color: #999;
                font-size: 32rpx;
            }
        }

        .total-calories {
            margin-top: 30rpx;
            font-size: 28rpx;
            font-weight: bold;
            color: #ff6b35;
            text-align: right;
        }
    }

    .popup-actions {
        margin-top: 30rpx;

        .save-btn {
            background-color: #ff6b35;
            color: #fff;
            text-align: center;
            padding: 20rpx;
            border-radius: 12rpx;
            font-size: 28rpx;
        }
    }
}
</style>
